<?php
/*

Version 0.1
SEMF - Web Desiging Framework for Sport Event Managment
Copyright (C) 2006, SEMF Developers

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

*/
include_once("login_util.php");

if(!isset($project_home))
{
	$project_home = $_GET["project_home"];
	$req_module_name = $_GET["req_module"];
}
if(!isset($project_database))
{
	$project_database = $_GET["project_database"];
}

if(!isset($semf_root))
{
	$semf_root = "../../";
}

$project_home = $semf_root.$project_home;

$db_info = get_database_info($project_home);


$project_database = $db_info["db_name"];
$mysql_server = $db_info["db_server"];
$mysql_password = $db_info["db_password"];

if(!isset($project_database))
{
	$project_database = 'semf_test';
}
if(!isset($mysql_server))
{
	$mysql_server = 'localhost';
}
if(!isset($mysql_password))
{
	$mysql_password = '';
}
if(!isset($project_home))
{
	$project_home = "./";
}

$files = array();
$d = dir($project_home);
// Loop through all of the files:
$i = 0;
while (false !== ($file = $d->read()))
{
	// If the file is not this file, and does not start with a '.' or '~'
	// and does not end in LCK, then store it for later display:
	if ( ($file{0} != '.') &&
		 ($file{0} != '~') &&
		 (substr($file, -3) != 'php') &&
		 is_dir($project_home.$file))
	{
		if($file == "store")
		{
			continue;
		}
		$files[$i++] = $file;
	}
}

/** handle the sql creatation part */
$link = mysql_connect($mysql_server, 'root', $mysql_password);
/*if(!isset($req_module_name))
{
	if (!$link) 
	{
	   die('Could not connect: ' . mysql_error());
	}
	if (mysql_select_db($project_database)) //just refresh the database
	{
		mysql_query("drop DATABASE ".$project_database);
	}
	
	if (!mysql_query("CREATE DATABASE ".$project_database))
	{
	   echo 'Error creating database: ' . mysql_error() . "\n";
	}
}*/
if(mysql_select_db($project_database) == false)
{
	
	if (!mysql_query("CREATE DATABASE ".$project_database))
	{
	   echo 'Error creating database: ' . mysql_error() . "\n";
	}
	
	mysql_select_db($project_database) || die("Error accessing database: ".mysql_error()."\n");
}


$sql_types = array(	"Text"=> "TEXT",
					"Number"=> "INT",
					"Date"=> "DATE",
					"Time"=> "TIME",
					"Image"=> "TEXT");

foreach($files as $file)
{
	$module_name = $file;
	
	if(isset($req_module_name) && $req_module_name != $module_name)
	{
		continue;
	}
	
	$module_xml = $project_home.$file."/"."module.xml";
	
	$doc = new DOMDocument();
	$doc->load($module_xml);
	
	if($doc == NULL || $doc->documentElement == NULL)
	{
		exit();
	}
	$table_elements = $doc->documentElement->childNodes;
	
	
	foreach ($table_elements as $table_element)
	{
		if($table_element->nodeType != XML_ELEMENT_NODE)
		{
			continue;
		}
		$sql_text = "";
		$is_interface = $table_element->getAttribute("interface");
		if($is_interface == "yes")
		{
			continue;
		}
		$table_name = $table_element->getAttribute("name");
		$sql_text .= "CREATE TABLE ".$module_name."_".$table_name."(\n";
		$sql_text .= "ID INT NOT NULL AUTO_INCREMENT,\n";
		$sql_text .= "__newly_created BOOLEAN, \n";
		$sql_text .= "extra TEXT";
		
		
		$direct_fields = array();
		
		$all_fields = array();
		$field_elements = $table_element->childNodes;
		
		foreach($field_elements as $field_element)
		{		
			if($field_element->tagName != "field")
			{
				continue;
			}
			$field_info = array(
					"name"=> $field_element->getAttribute("name"),
					"type"=> $field_element->getAttribute("type"),
					"isarray"=> $field_element->getAttribute("isarray"));
					
			$direct_fields[$field_element->getAttribute("name")] = 1;
			
			$all_fields[count($all_fields)] = $field_info;		
		}
		
		//load all the inherited information..
		$inherited_elements = $table_element->childNodes;
		foreach($inherited_elements as $inherited_element)
		{
			if($inherited_element->tagName != "inherited")
			{
				continue;
			}
			$inherited_table = $inherited_element->nodeValue;
			$pos = strpos($inherited_table, ".");
			$inherited_table_owner_module = substr($inherited_table, 0, $pos);
			$inherited_table_name = trim(substr($inherited_table, $pos+1));
			
			
			$inherited_module_xml = $project_home.trim($inherited_table_owner_module)."/module.xml";
			$inherited_doc = new DOMDocument();
			$inherited_doc->load($inherited_module_xml);
			
			
			
			$inherited_table_elements = $inherited_doc->documentElement->childNodes;
			foreach ($inherited_table_elements as $inherited_table_element)
			{
				if($inherited_table_element->nodeType != XML_ELEMENT_NODE)
				{
					continue;
				}
				if($inherited_table_element->getAttribute("name") == $inherited_table_name)
				{
					$inherited_field_elements = $inherited_table_element->childNodes;
					/*$inherited_field_elements = 
						array_merge($inherited_field_elements, $field_elements);*/
					foreach($inherited_field_elements as $inherited_field_element)
					{			
						if($inherited_field_element->tagName != "field")
						{
							continue;
						}
						$name = $inherited_field_element->getAttribute("name");
						if($direct_fields[$name] == 1)
						{
							continue;
						}
						/*$inherited_table_element-> removeChild($inherited_field_element);
						$table_element->appendChild($inherited_field_element); */
						$field_info = array(
								"name"=> $inherited_field_element->getAttribute("name"),
								"type"=> $inherited_field_element->getAttribute("type"),
								"isarray"=> $inherited_field_element->getAttribute("isarray"));
						
						$all_fields[count($all_fields)] = $field_info;
					}
					break;
				}
			}
		}
		
		
		foreach($all_fields as $field_info)
		{
			$midway_sql_text = "";

			$field_name = $field_info["name"];
			$field_type = $field_info["type"];
			
			$is_array = $field_info["isarray"];
			
			$sql_type = $sql_types[$field_type];
			if($sql_type == NULL)
			{
				//this means this is a table
				$sql_type = "INT";
				$field_type = substr($field_type, 6);
				$associated_table_name = str_replace(".", "_", $field_type);
			}
			if($is_array)
			{
				$midway_sql_text .= 
					"CREATE TABLE ".$module_name."_".$table_name."_".$field_name."(\n";
				$midway_sql_text .= "ID INT NOT NULL,\n";
				$midway_sql_text .= $field_name." ".$sql_type.",\n";
				$midway_sql_text .= "PRIMARY KEY(ID, ".$field_name.")";
				$midway_sql_text .= ");\n\n";
				//mysql_query($midway_sql_text) || die('MySQL Error: '. mysql_error());
				execute_query($midway_sql_text, $dont_echo);
			}
			else
			{
				$sql_text .= ",\n";
				$sql_text .= $field_name." ";
				$sql_text .= $sql_type;
			}
			
		}
		
		$sql_text .= ",\n";
		$sql_text .= "PRIMARY KEY(ID)";
		
		$sql_text .= ");\n\n";
		//mysql_query($sql_text) || die('MySQL Error: '. mysql_error());
		//$sql_text .= $midway_sql_text;
		execute_query($sql_text, $dont_echo);
	}
}

function execute_query($sql, $dont_echo)
{
	mysql_query($sql); //no need to report error
	
	if($dont_echo != 1)
	{
		echo str_replace("\n", "<br/>\n", $sql)."\n";
	}
}
//echo $sql_text;

// Free resultset
//mysql_free_result($result);

// Closing connection
mysql_close($link);
?>
